<template>
	<view class="container">
		<!-- 添加天地图容器，放在最上面使其铺满整个页面 -->
		<view class="map-container" id="mapContainer"></view>
		
		<!-- 将设备信息改为浮动在地图上方 -->
		<view class="header floating-header">
			<view class="detail-info">
				<text>序号</text>
				<text>{{ device.id }}</text>
			</view>
			<view class="detail-info">
				<text>设备名</text>
				<text>{{ device.name }}</text>
			</view>
			<view class="detail-info">
				<text>所属单位</text>
				<text>{{ device.unit }}</text>
			</view>
			<view class="detail-info">
				<text>设备状态</text>
				<text>{{ device.status }}</text>
			</view>
		</view>
		
		<!-- 抽屉式滚动视图容器 -->
		<view class="drawer-container" :class="{'drawer-expanded': isDrawerExpanded}">
			<!-- 抽屉把手 -->
			<view class="drawer-handle" @touchstart="handleTouchStart" @touchmove="handleTouchMove" @touchend="handleTouchEnd">
				<view class="drawer-indicator"></view>
			</view>
			
			<!-- 抽屉内容 -->
			<scroll-view class="data-panel" scroll-y="true">
				<view class="panel-card">
					<view class="panel-title">实时能耗</view>
					<view class="energy-display">
						<view class="energy-value">{{ currentEnergy }}</view>
						<view class="energy-unit">kW·h</view>
					</view>
					<view class="energy-chart">
						<!-- 这里可以添加能耗图表组件 -->
						<view class="chart-placeholder">
							<view class="chart-bar" v-for="(value, index) in recentEnergyData" :key="index"
								:style="{ height: value + '%', backgroundColor: getBarColor(value) }">
							</view>
						</view>
					</view>
				</view>
				
				<view class="panel-card">
					<view class="panel-title">远程控制</view>
					<view class="control-panel">
						<view class="control-item">
							<text>开/关状态</text>
							<switch @change="handleRemoteControlChange" :checked="isDeviceOn" color="#007aff" />
						</view>
						<view class="control-item">
							<text>自动模式</text>
							<switch @change="handleAutoModeChange" :checked="isAutoMode" color="#007aff" />
						</view>
						<view class="control-logs">
							<view class="log-title">最近操作记录</view>
							<view class="log-item" v-for="(log, index) in controlLogs" :key="index">
								{{ log.time }} - {{ log.action }}
							</view>
						</view>
					</view>
				</view>
				
				<view class="panel-card">
					<view class="panel-title">能耗统计</view>
					<view class="stats-tabs">
						<view 
							class="tab-item" 
							:class="{ active: activeStatTab === 'day' }" 
							@click="activeStatTab = 'day'"
						>日</view>
						<view 
							class="tab-item" 
							:class="{ active: activeStatTab === 'week' }" 
							@click="activeStatTab = 'week'"
						>周</view>
						<view 
							class="tab-item" 
							:class="{ active: activeStatTab === 'month' }" 
							@click="activeStatTab = 'month'"
						>月</view>
					</view>
					<view class="stats-content">
						<view class="stats-summary">
							<view class="summary-item">
								<text class="summary-label">总能耗</text>
								<text class="summary-value">{{ energyStats.total }} kW·h</text>
							</view>
							<view class="summary-item">
								<text class="summary-label">平均能耗</text>
								<text class="summary-value">{{ energyStats.average }} kW·h</text>
							</view>
							<view class="summary-item">
								<text class="summary-label">峰值能耗</text>
								<text class="summary-value">{{ energyStats.peak }} kW·h</text>
							</view>
						</view>
					</view>
				</view>
			</scroll-view>
		</view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			device: {},
			map: null,
			marker: null,
			// 设备地理位置坐标（示例坐标，应根据实际需求修改）
			deviceLocation: {
				lng: 116.397428,
				lat: 39.90923
			},
			// 实时能耗数据
			currentEnergy: 5.8,
			recentEnergyData: [30, 45, 60, 35, 50, 70, 55, 40],
			
			// 控制状态
			isDeviceOn: true,
			isAutoMode: false,
			controlLogs: [
				{ time: '2023-06-10 08:30', action: '设备开启' },
				{ time: '2023-06-09 18:45', action: '设备关闭' },
				{ time: '2023-06-09 07:15', action: '设备开启' }
			],
			
			// 能耗统计
			activeStatTab: 'day',
			energyStats: {
				total: 142.5,
				average: 5.9,
				peak: 8.7
			},
			
			// 抽屉状态
			isDrawerExpanded: false,
			touchStartY: 0,
			touchMoveY: 0,
			drawerHeight: 0,
			minDrawerHeight: 250, // 最小高度 (rpx)
			maxDrawerHeight: 0,   // 最大高度，将在mounted中计算
		};
	},
	created() {
		// 获取页面参数
		const pages = getCurrentPages();
		const currentPage = pages[pages.length - 1];
		const options = currentPage.$page.options;
		
		// 解码参数
		this.device = {
			id: options.id,
			name: decodeURIComponent(options.name),
			type: decodeURIComponent(options.type),
			status: decodeURIComponent(options.status),
			unit: decodeURIComponent(options.unit),
			controlTime: decodeURIComponent(options.controlTime),
			area: decodeURIComponent(options.area || options.controlType || ''), // 兼容新旧字段
			controlStatus: decodeURIComponent(options.controlStatus)
		};
	},
	mounted() {
		// 在页面挂载后初始化天地图
		this.initTiandituMap();
		
		// 计算抽屉最大高度
		const systemInfo = uni.getSystemInfoSync();
		// 将屏幕高度的80%作为最大高度
		this.maxDrawerHeight = systemInfo.windowHeight * 0.8;
		// 设置初始高度为最小高度
		this.drawerHeight = this.minDrawerHeight;
	},
	methods: {
		initTiandituMap() {
			// 动态加载天地图JavaScript API
			const script = document.createElement('script');
			script.src = 'https://api.tianditu.gov.cn/api?v=4.0&tk=8ce60daf6f5ef3d33163695c640dd723';
			script.onload = () => {
				this.loadMap();
			};
			document.head.appendChild(script);
		},
		loadMap() {
			// 确保天地图API已加载
			if (typeof T === 'undefined') {
				console.error('天地图API未加载成功');
				return;
			}
			
			// 初始化地图 - 指定只使用矢量地图
			this.map = new T.Map('mapContainer', {
				projection: 'EPSG:4326'
			});
			
			// 添加矢量图层
			const vecLayer = new T.TileLayer(T.TMAP_NORMAL_MAP);
			this.map.addLayer(vecLayer);
			
			// 设置地图中心点和缩放级别
			this.map.centerAndZoom(new T.LngLat(this.deviceLocation.lng, this.deviceLocation.lat), 13);
			
			// 移除了地图类型切换控件，只保留缩放控件
			//this.map.addControl(new T.Control.Zoom());
			
			// 添加设备位置标记
			this.addDeviceMarker();
		},
		addDeviceMarker() {
			// 创建标记点
			const marker = new T.Marker(new T.LngLat(this.deviceLocation.lng, this.deviceLocation.lat));
			
			// 将标记点添加到地图
			this.map.addOverLay(marker);
			
			// 保存标记点引用
			this.marker = marker;
			
			// 添加信息窗口
			const infoWindow = new T.InfoWindow(this.device.name);
			marker.addEventListener('click', () => {
				marker.openInfoWindow(infoWindow);
			});
		},
		
		// 获取能耗柱状图颜色
		getBarColor(value) {
			if (value < 40) return '#4CD964'; // 低能耗 - 绿色
			if (value < 70) return '#FFCC00'; // 中能耗 - 黄色
			return '#FF3B30'; // 高能耗 - 红色
		},
		
		// 远程控制开关状态变化
		handleRemoteControlChange(e) {
			this.isDeviceOn = e.detail.value;
			const action = this.isDeviceOn ? '设备开启' : '设备关闭';
			const now = new Date();
			const timeStr = `${now.getFullYear()}-${(now.getMonth()+1).toString().padStart(2, '0')}-${now.getDate().toString().padStart(2, '0')} ${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`;
			
			// 添加到操作日志
			this.controlLogs.unshift({
				time: timeStr,
				action: action
			});
			
			// 保持日志最多显示5条
			if (this.controlLogs.length > 5) {
				this.controlLogs.pop();
			}
			
			// 在实际应用中，这里应该发送请求到服务器
			uni.showToast({
				title: action,
				icon: 'none'
			});
		},
		
		// 自动模式开关状态变化
		handleAutoModeChange(e) {
			this.isAutoMode = e.detail.value;
			const action = this.isAutoMode ? '自动模式开启' : '自动模式关闭';
			
			// 在实际应用中，这里应该发送请求到服务器
			uni.showToast({
				title: action,
				icon: 'none'
			});
		},
		
		// 抽屉触摸开始
		handleTouchStart(e) {
			this.touchStartY = e.touches[0].clientY;
		},
		
		// 抽屉触摸移动
		handleTouchMove(e) {
			const currentY = e.touches[0].clientY;
			const deltaY = this.touchStartY - currentY;
			
			// 计算新的抽屉高度
			let newHeight = this.drawerHeight + deltaY;
			
			// 限制高度在最小和最大范围内
			if (newHeight < this.minDrawerHeight) newHeight = this.minDrawerHeight;
			if (newHeight > this.maxDrawerHeight) newHeight = this.maxDrawerHeight;
			
			// 更新抽屉高度
			this.drawerHeight = newHeight;
			
			// 根据高度更新展开状态
			this.isDrawerExpanded = newHeight > (this.minDrawerHeight + 100);
			
			// 更新起始位置，实现平滑跟随
			this.touchStartY = currentY;
		},
		
		// 抽屉触摸结束
		handleTouchEnd() {
			// 根据当前高度决定是展开还是收起
			if (this.drawerHeight > (this.minDrawerHeight + this.maxDrawerHeight) / 2) {
				// 如果超过中点，展开抽屉
				this.expandDrawer();
			} else {
				// 否则收起抽屉
				this.collapseDrawer();
			}
		},
		
		// 展开抽屉
		expandDrawer() {
			this.isDrawerExpanded = true;
			this.drawerHeight = this.maxDrawerHeight;
		},
		
		// 收起抽屉
		collapseDrawer() {
			this.isDrawerExpanded = false;
			this.drawerHeight = this.minDrawerHeight;
		}
	}
};
</script>

<style scoped>
.container {
	display: flex;
	flex-direction: column;
	height: 100vh;
	width: 100%;
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	overflow: hidden;
}
.device-detail {
	padding: 20px;
	background-color: #f9f9f9;
	border-radius: 10px;
	box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
/* 将header修改为悬浮样式 */
.floating-header {
	position: absolute;
	top: 150rpx;
	left: 50%;
	transform: translateX(-50%);
	width: 700rpx;
	display: flex;
	justify-content: space-between;
	flex-direction: row;
	background-color: rgba(255, 255, 255, 0.9);
	align-items: center;
	text-align: center;
	border-radius: 10rpx;
	box-shadow: 0 0 10rpx rgba(0, 0, 0, 0.2);
	z-index: 1000;
	padding: 20rpx;
}
.detail-info{
	display: flex;
	flex-direction: column;
}
/* 地图容器样式 - 修改为铺满整个页面 */
.map-container {
	width: 100%;
	height: 100vh;
	position: absolute;
	top: 0;
	left: 0;
	z-index: 10;
}

/* 抽屉式数据面板样式 */
.drawer-container {
	position: fixed;
	bottom: 0;
	left: 0;
	width: 100%;
	background-color: rgba(255, 255, 255, 0.95);
	border-radius: 20rpx 20rpx 0 0;
	box-shadow: 0 -5rpx 15rpx rgba(0, 0, 0, 0.1);
	z-index: 900;
	transition: height 0.3s ease-out;
	height: 250rpx; /* 初始高度 */
}

.drawer-expanded {
	height: 80vh; /* 展开时的高度 */
}

.drawer-handle {
	width: 100%;
	height: 40rpx;
	display: flex;
	justify-content: center;
	align-items: center;
	padding: 20rpx 0;
	cursor: grab;
}

.drawer-indicator {
	width: 60rpx;
	height: 6rpx;
	background-color: #c0c0c0;
	border-radius: 3rpx;
}

.data-panel {
	height: calc(100% - 60rpx);
	padding: 0 20rpx 20rpx 20rpx;
}

.panel-card {
	margin-bottom: 30rpx;
	padding: 20rpx;
	background-color: #fff;
	border-radius: 15rpx;
	box-shadow: 0 5rpx 15rpx rgba(0, 0, 0, 0.1);
}

.panel-title {
	font-size: 32rpx;
	font-weight: bold;
	margin-bottom: 20rpx;
	color: #333;
	border-bottom: 2rpx solid #f0f0f0;
	padding-bottom: 10rpx;
}

/* 实时能耗样式 */
.energy-display {
	display: flex;
	align-items: baseline;
	margin-bottom: 20rpx;
}

.energy-value {
	font-size: 50rpx;
	font-weight: bold;
	color: #007aff;
}

.energy-unit {
	font-size: 28rpx;
	color: #666;
	margin-left: 10rpx;
}

.energy-chart {
	height: 150rpx;
	margin-top: 20rpx;
}

.chart-placeholder {
	height: 100%;
	display: flex;
	justify-content: space-between;
	align-items: flex-end;
}

.chart-bar {
	width: 10%;
	border-radius: 10rpx 10rpx 0 0;
	transition: height 0.3s ease;
}

/* 控制面板样式 */
.control-panel {
	padding: 10rpx;
}

.control-item {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 20rpx;
	padding: 10rpx 0;
}

.control-logs {
	margin-top: 30rpx;
	border-top: 2rpx dashed #eee;
	padding-top: 20rpx;
}

.log-title {
	font-size: 28rpx;
	color: #666;
	margin-bottom: 10rpx;
}

.log-item {
	font-size: 24rpx;
	color: #999;
	margin-bottom: 5rpx;
}

/* 统计面板样式 */
.stats-tabs {
	display: flex;
	border-bottom: 2rpx solid #eee;
	margin-bottom: 20rpx;
}

.tab-item {
	padding: 15rpx 30rpx;
	font-size: 28rpx;
	color: #666;
	position: relative;
}

.tab-item.active {
	color: #007aff;
}

.tab-item.active:after {
	content: '';
	position: absolute;
	bottom: -2rpx;
	left: 0;
	width: 100%;
	height: 4rpx;
	background-color: #007aff;
}

.stats-summary {
	display: flex;
	justify-content: space-between;
	flex-wrap: wrap;
}

.summary-item {
	width: 30%;
	text-align: center;
	margin-bottom: 20rpx;
}

.summary-label {
	font-size: 24rpx;
	color: #999;
	display: block;
	margin-bottom: 10rpx;
}

.summary-value {
	font-size: 28rpx;
	color: #333;
	font-weight: bold;
}

h1 {
	font-size: 24px;
	margin-bottom: 20px;
}
p {
	font-size: 18px;
	margin: 5px 0;
}
</style>